package com.bjpowernode.controller;
import com.bjpowernode.beans.Stu;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/stu")
public class StuController {

    @RequestMapping("get.action")
    public Map get(@Valid Stu stu, BindingResult bindingResult){
        HashMap hashMap=new HashMap();
        hashMap.put("result","success");
        hashMap.put("data",stu);
        if(bindingResult.hasErrors()){
            hashMap.put("result","error");
            ArrayList errorArrayList=new ArrayList();
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                HashMap errorMap=new HashMap();
                errorMap.put("fieldName",fieldError.getField());
                errorMap.put("fieldValue",fieldError.getRejectedValue());
                errorMap.put("fieldMessage",fieldError.getDefaultMessage());
                errorArrayList.add(errorMap);
            }
            hashMap.put("errorData",errorArrayList);
            hashMap.put("data",null);
        }
        return hashMap;
    }
}
